<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Map, View, Overlay } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import ImageWMS from 'ol/source/ImageWMS'
import ImageLayer from 'ol/layer/Image'
import { GeoJSON, WFS } from 'ol/format'
import { Draw, Select, Modify } from 'ol/interaction'
import { DragBox } from 'ol/interaction'
import { Feature, Collection } from 'ol'
import { Style, Stroke, Fill, Circle } from 'ol/style'
import { platformModifierKeyOnly } from 'ol/events/condition'
import { getCenter } from 'ol/extent'
import { transform } from 'ol/proj'
import 'element-plus/dist/index.css'
import 'ol/ol.css'
import FeatureEditDialog from './FeatureEditDialog.vue';// 导入封装的对话框组件

const mapRef = ref(null)
const map = ref(null)
const vectorSource = ref(null)
const vectorLayer = ref(null)
const hasFeatures = ref(false)
const currentBaseMap = ref('vector') // 当前底图类型：vector(矢量), image(影像), terrain(地形)

// GeoServer相关变量
const geoserverWmsLayer = ref(null)
const isWmsLayerVisible = ref(false)
const geoserverWfsLayer = ref(null)
const geoserverWfsSource = ref(null)
const isWfsLayerVisible = ref(false)
// 使用相对路径配合Vite代理来避免CORS问题
const wmsUrl = '/geoserver/webgis2305/wms'
const wmsLayerName = 'webgis2305:populated_places'
// const wfsWorkspace = 'web2305'
// 使用代理路径而不是直接URL，避免CORS问题
const wfsUrl = '/geoserver/web2305/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=web2305%3Abou2_4l&outputFormat=application%2Fjson'

// 数据类型映射 - 扩展支持更多类型
const typeMap = {
  'city': 'city',
  'bou2_4l': 'bou2_4l',
  'bou2_4p': 'bou2_4p',
  'point': 'city',
  'line': 'bou2_4l',
  'polygon': 'bou2_4p',
  'Point': 'city',
  'LineString': 'bou2_4l',
  'Polygon': 'bou2_4p',
  'MultiPoint': 'city',
  'MultiLineString': 'bou2_4l',
  'MultiPolygon': 'bou2_4p'
}

let draw = null

// 对话框相关状态
const dialogVisible = ref(false)
const currentFeature = ref(null)
const currentTypeName = ref('')

// 删除功能相关状态
const isDeleting = ref(false)
const selectedFeatures = ref([])
let selectInteraction = null

// 修改功能相关状态
const isEditing = ref(false)
const modifiedFeatures = ref([])
let modifyInteraction = null
let modifiedSource = null

// 查询功能相关状态
const isQuerying = ref(false)
const querySelectInteraction = ref(null)
const queryBoxInteraction = ref(null)
let propertyOverlay = ref(null)

// 默认属性模板 - 点要素
const defaultPointProperties = reactive({
  area: 0,
  perimeter: 0,
  res1_4m0_: 1,
  res1_4m0_i: 61,
  gbcode: 31010,
  name: "新建城市",
  adcode93: 110100,
  adcode99: 110100,
  adclass: 1,
  pinyin: "NewCity",
  polygonid: 0,
  scale: 1,
  angle: 0
})

// 线要素默认属性模板
const defaultLineProperties = reactive({
  fnode_: 2,
  tnode_: 7,
  lpoly_: 2,
  rpoly_: 3,
  length: 7.743,
  bou2_4m_: 1,
  bou2_4m_id: 23,
  gbcode: 61030
})

// 面要素默认属性模板
const defaultPolygonProperties = reactive({
  area: 0,
  perimeter: 0.023,
  bou2_4m_: 47,
  bou2_4m_id: 447,
  adcode93: 210000,
  adcode99: 210000,
  name: "辽宁省"
})

// 当前编辑的属性
const featureProperties = reactive({})

// 初始化矢量图层
const initVectorLayer = () => {
  // 创建矢量数据源
  vectorSource.value = new VectorSource()
  
  // 创建矢量图层
  vectorLayer.value = new VectorLayer({
    source: vectorSource.value
  })
  
  // 添加矢量图层到地图
  map.value.addLayer(vectorLayer.value)
}

// 开始删除要素模式
const startDeleteFeature = () => {
  if (isDeleting.value) {
    stopDeleteFeature();
    return;
  }

  // 先移除绘制交互
  stopDrawing();
  
  // 设置为删除模式
  isDeleting.value = true;
  
  // 创建选择交互
  selectInteraction = new Select({
    style: new Style({
      fill: new Fill({
        color: 'rgba(255, 0, 0, 0.2)'
      }),
      stroke: new Stroke({
        color: '#ff0000',
        width: 2
      }),
      image: new Circle({
        radius: 6,
        fill: new Fill({
          color: 'rgba(255, 0, 0, 0.5)'
        }),
        stroke: new Stroke({
          color: '#ff0000',
          width: 2
        })
      })
    }),
    multi: true
  });
  
  // 添加选择事件监听
  selectInteraction.getFeatures().on('add', (event) => {
    const feature = event.element;
    selectedFeatures.value.push(feature);
    console.log('选中了要素:', feature.getId());
  });
  
  selectInteraction.getFeatures().on('remove', (event) => {
    const feature = event.element;
    selectedFeatures.value = selectedFeatures.value.filter(f => f !== feature);
    console.log('取消选中要素:', feature.getId());
  });
  
  map.value.addInteraction(selectInteraction);
  console.log('进入要素删除模式');
};

// 停止删除要素模式
const stopDeleteFeature = () => {
  if (selectInteraction) {
    map.value.removeInteraction(selectInteraction);
    selectInteraction = null;
  }
  isDeleting.value = false;
  selectedFeatures.value = [];
  console.log('退出要素删除模式');
};

// 删除选中的要素
const deleteSelectedFeatures = async () => {
  if (selectedFeatures.value.length === 0) {
    console.log('没有选中的要素');
    alert('没有选中的要素');
    return;
  }

  // 为每个删除的要素确保正确设置ID，即使原始要素没有ID也创建临时ID
  const deleteFeatures = selectedFeatures.value.map((feature, index) => {
    const deletedFeature = feature.clone();
    deletedFeature.setGeometryName('geom');
    
    // 确保要素有ID，如果没有则创建临时ID
    const originalId = feature.getId();
    if (originalId) {
      deletedFeature.setId(originalId);
    } else {
      // 创建临时ID，使用时间戳和索引确保唯一性
      const tempId = `temp_${Date.now()}_${index}`;
      deletedFeature.setId(tempId);
      console.log(`为要素创建临时ID: ${tempId} 用于删除操作`);
    }
    
    return deletedFeature;
  });

  try {
    // 确定要素类型
    const firstFeature = selectedFeatures.value[0];
    const featureType = firstFeature.getGeometry().getType();
    
    // 过滤出有原始ID的要素用于WFS删除请求
    const featuresWithId = deleteFeatures.filter(feature => 
      feature.getId() && !feature.getId().toString().startsWith('temp_')
    );
    
    // 如果有带ID的要素，执行WFS删除请求
    if (featuresWithId.length > 0) {
      await wfsRequest(featuresWithId, 'delete', featureType);
    } else {
      console.log('所选要素没有有效的持久化ID，只从本地数据源移除');
    }
    
    // 从本地数据源中移除要素
    selectedFeatures.value.forEach(feature => {
      if (vectorSource.value && vectorSource.value.getFeatures().includes(feature)) {
        vectorSource.value.removeFeature(feature);
      }
      if (geoserverWfsSource.value && geoserverWfsSource.value.getFeatures().includes(feature)) {
        geoserverWfsSource.value.removeFeature(feature);
      }
    });
    
    // 清空选中列表
    selectedFeatures.value = [];
    hasFeatures.value = vectorSource.value ? vectorSource.value.getFeatures().length > 0 : false;
    
    // 显示成功消息
    console.log('成功删除要素');
    alert('要素删除成功！');
  } catch (error) {
    console.error('删除要素失败:', error);
    alert('删除要素失败: ' + error.message);
  }
};

// 加载GeoServer WFS图层
const loadGeoserverWfsLayer = () => {
  // 创建WFS数据源
  geoserverWfsSource.value = new VectorSource({
    format: new GeoJSON(),
    url: wfsUrl
  })
  
  // 创建WFS图层
  geoserverWfsLayer.value = new VectorLayer({
    source: geoserverWfsSource.value,
    style: function() {
      // 可以根据需要自定义样式
      return new Style({
        stroke: new Stroke({
          color: '#FF0000',
          width: 2
        }),
        fill: new Fill({
          color: 'rgba(255, 0, 0, 0.1)'
        })
      })
    }
  })
  
  // 添加到地图
  if(!map.value.getLayers().getArray().includes(geoserverWfsLayer.value)){
    map.value.addLayer(geoserverWfsLayer.value)
  }
  
  isWfsLayerVisible.value = true
  
  // 监听数据加载完成事件
  geoserverWfsSource.value.once('featuresloadend', () => {
    console.log('WFS图层加载完成，要素数量：', geoserverWfsSource.value.getFeatures().length)
    
    // 检查是否有要素
    if (geoserverWfsSource.value.getFeatures().length > 0) {
      // 获取第一个要素的几何类型
      const geomType = geoserverWfsSource.value.getFeatures()[0].getGeometry().getType()
      console.log('WFS图层几何类型:', geomType)
    }
  })
}

// 移除GeoServer WFS图层
const removeGeoserverWfsLayer = () => {
  if (geoserverWfsLayer.value && map.value) {
    map.value.removeLayer(geoserverWfsLayer.value)
    geoserverWfsLayer.value = null
    geoserverWfsSource.value = null
    isWfsLayerVisible.value = false
  }
}

// 切换GeoServer WFS图层显示状态
const toggleWfsLayer = () => {
  if (isWfsLayerVisible.value) {
    removeGeoserverWfsLayer()
  } else {
    loadGeoserverWfsLayer()
  }
 }

// 添加和绘制要素
const addFeature = (type) => {
  vectorLayer.value.setSource(null)
  // 更新全局的vectorSource.value引用
  vectorSource.value = new VectorSource({
    format: new GeoJSON(),
    url: `/geoserver/web2305/ows?service=WFS&version=2.0.0&request=GetFeature&typeName=web2305%3A${typeMap[type]}&outputFormat=application%2Fjson`,
    crossOrigin: 'anonymous'
  })
  vectorLayer.value.setSource(vectorSource.value)
  if(!map.value.getLayers().getArray().includes(vectorLayer.value)){
    map.value.addLayer(vectorLayer.value)
  }

  // 移除之前的绘制交互
  if(map.value.getInteractions().getArray().includes(draw)){
    map.value.removeInteraction(draw)
  }

  // 等待要素加载完成后添加绘制交互
  vectorSource.value.once('featuresloadend', () => {
    hasFeatures.value = vectorSource.value.getFeatures().length > 0
    
    // 如果有要素，获取其几何类型
    if (vectorSource.value.getFeatures().length > 0) {
      const geomType = vectorSource.value.getFeatures()[0].getGeometry().getType()
      console.log('几何类型:', geomType)
      
      // 创建绘制交互
      draw = new Draw({
        source: vectorSource.value,
        type: geomType
      })
      map.value.addInteraction(draw)

      // 监听绘制结束事件
      draw.on('drawend', (evt) => {
        console.log('绘制结束事件触发:', {
          type: type,
          geomType: geomType,
          featureGeomType: evt.feature.getGeometry().getType()
        })
        
        // 简化判断逻辑，只根据类型判断，不依赖geomType
        let showDialog = false
        
        if (type === 'city') {
          showDialog = true
        } else if (type === 'bou2_4l') {
          showDialog = true
        } else if (type === 'bou2_4p') {
          showDialog = true // 面要素也显示对话框
        }
        
        console.log('是否显示对话框:', showDialog)
        
        if (showDialog) {
          // 保存当前要素和类型
          currentFeature.value = evt.feature
          currentTypeName.value = typeMap[type]
          
          // 清空featureProperties避免属性混淆
          Object.keys(featureProperties).forEach(key => delete featureProperties[key])
          
          // 根据要素类型设置默认属性
          if (type === 'city') {
            console.log('加载点要素默认属性')
            Object.assign(featureProperties, defaultPointProperties)
          } else if (type === 'bou2_4l') {
            console.log('加载线要素默认属性')
            Object.assign(featureProperties, defaultLineProperties)
          } else if (type === 'bou2_4p') {
            console.log('加载面要素默认属性')
            Object.assign(featureProperties, defaultPolygonProperties)
          }
          
          console.log('当前编辑的属性:', featureProperties)
          console.log('当前类型:', currentTypeName.value)
          
          // 强制显示对话框
          console.log('显示属性编辑对话框')
          // 使用setTimeout确保Vue响应式系统能够正确更新
          setTimeout(() => {
            dialogVisible.value = true
            console.log('对话框可见性设置为:', dialogVisible.value)
          }, 0)
        } else {
          // 对于面，直接提交
          console.log('直接提交非对话框要素')
          const newgeom = evt.feature.getGeometry().clone()
          const newFeature = new Feature()
          newFeature.setGeometryName('geom')
          newFeature.setGeometry(newgeom)
          submitFeatureData([newFeature], typeMap[type])
        }
      })
    }
  })
}

// 下载功能已移除

// 加载GeoServer WMS图层
const loadGeoserverWmsLayer = () => {
  if (!map.value) return
  
  // 如果图层已存在，先移除
  if (geoserverWmsLayer.value) {
    map.value.removeLayer(geoserverWmsLayer.value)
    geoserverWmsLayer.value = null
  }
  
  // 创建WMS图层
  geoserverWmsLayer.value = new ImageLayer({
    source: new ImageWMS({
      url: wmsUrl,
      params: {
        'LAYERS': wmsLayerName,
        'TILED': true
      },
      ratio: 1,
      serverType: 'geoserver'
    })
  })
  
  // 添加到地图
  map.value.addLayer(geoserverWmsLayer.value)
  isWmsLayerVisible.value = true
}

// 移除GeoServer WMS图层
const removeGeoServerWMSLayer = () => {
  if (geoserverWmsLayer.value && map.value) {
    map.value.removeLayer(geoserverWmsLayer.value)
    geoserverWmsLayer.value = null
    isWmsLayerVisible.value = false
  }
}

// 切换GeoServer WMS图层显示状态
const toggleWmsLayer = () => {
  if (isWmsLayerVisible.value) {
    removeGeoserverWmsLayer()
  } else {
    loadGeoserverWmsLayer()
  }
}

// GeoServer相关功能 - WFS图层显示/隐藏已移除

// 上传矢量数据到GeoServer
const uploadToGeoserver = async () => {
  if (!vectorSource.value) {
    alert('请先添加矢量数据')
    return
  }
  
  const features = vectorSource.value.getFeatures()
  if (features.length === 0) {
    alert('没有可上传的矢量数据')
    return
  }
  
  try {
    // 为要素添加必要的属性
    features.forEach(feature => {
      // 如果没有TYPE属性，添加一个默认值
      if (!feature.get('TYPE')) {
        feature.set('TYPE', 'highway')
      }
      
      // 确保geometryName正确设置
      feature.setGeometryName('geom')
    })
    
    // 创建WFS实例
    const wfs = new WFS()
    
    // 生成XML格式的WFS请求信息
    const node = wfs.writeTransaction(
      features, // 要插入的要素
      null,     // 要更新的要素
      null,     // 要删除的要素
      {
        srcName: 'EPSG:4326',
        featureNS: 'http://web2305.com', // 使用正确的命名空间URI
        featurePrefix: 'web2305',
        featureType: ['city'] // 直接指定要素类型
      }
    )
    
    // 将XML格式请求信息序列化为字符串格式
    const serializer = new XMLSerializer()
    const xmlString = serializer.serializeToString(node)
    
    // 使用GeoServer的WFS端点发送请求
    // 参考HTML示例中的端点路径
    const geoserverWfsEndpoint = '/geoserver/wfs'
    
    // 发送请求
    const response = await fetch(geoserverWfsEndpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'text/xml'
      },
      body: xmlString,
      credentials: 'include',
      mode: 'cors'
    })
    
    if (response.ok) {
      const result = await response.text()
      
      // 使用WFS的readTransactionResponse方法解析响应
      const transactRes = wfs.readTransactionResponse(result)
      
      // 构建成功消息
      let successMsg = transactRes.transactionSummary.totalInserted +
        " 个要素已成功插入!\n" +
        "插入ID: " + transactRes.insertIds + "\n" +
        transactRes.transactionSummary.totalUpdated + " 个要素已更新!\n" +
        transactRes.transactionSummary.totalDeleted + " 个要素已删除!"
      
      console.log('上传成功:', result)
      console.log('事务结果:', transactRes)
      alert(successMsg)
      
      // 数据已成功上传到GeoServer
    } else {
      throw new Error(`上传失败: ${response.status}`)
    }
  } catch (error) {
    console.error('上传错误:', error)
    
    // 提供详细的错误信息和解决建议
    if (error.message.includes('CORS')) {
      alert('上传失败: 跨域资源共享(CORS)错误。请：\n1. 确保GeoServer已配置CORS支持\n2. 或使用浏览器插件临时允许跨域请求')
      console.log('解决CORS问题的方法：\n1. 在GeoServer的web.xml中添加CORS过滤器\n2. 或配置Vite代理')
    } else {
      alert('上传失败: ' + error.message)
    }
  }
}

// 处理要素属性提交
const handleFeatureSubmit = (properties) => {
  if (!currentFeature.value) return
  
  const newgeom = currentFeature.value.getGeometry().clone()
  const newFeature = new Feature()
  newFeature.setGeometryName('geom')
  newFeature.setGeometry(newgeom)
  
  // 设置所有属性
  Object.entries(properties).forEach(([key, value]) => {
    newFeature.set(key, value)
  })
  
  // 提交到服务器
  submitFeatureData([newFeature], currentTypeName.value)
  
  // 关闭对话框
  dialogVisible.value = false
}

// 处理编辑取消
const handleFeatureCancel = () => {
  dialogVisible.value = false
  currentFeature.value = null
}

// 提交要素数据到服务器的共用函数
const submitFeatureData = (features, featureType) => {
  // 创建WFS事务
  const wfsTranaction = new WFS().writeTransaction(features, null, null, {
    featureNS: 'http://web2305.com',
    featurePrefix: 'web2305',
    featureType: featureType,
  })
  const wfsString = new XMLSerializer().serializeToString(wfsTranaction)

  // 发送WFS请求 - 使用代理路径
  const xhr = new XMLHttpRequest()
  xhr.open('POST', '/geoserver/web2305/ows?service=WFS', true)
  xhr.setRequestHeader('Content-Type', 'text/xml')
  xhr.send(wfsString)

  xhr.onreadystatechange = function () {
    if(xhr.status === 200 && xhr.readyState === 4) {
      console.log('成功响应:', xhr.responseText)
      alert('要素添加成功！')
    }
  }
}

// 停止绘制功能
const stopDrawing = () => {
  // 移除所有绘制交互
  if (map.value) {
    // 检查并移除draw交互
    if (draw && map.value.getInteractions().getArray().includes(draw)) {
      map.value.removeInteraction(draw)
      draw = null
    }
    
    // 移除任何可能存在的Draw类型交互
    const interactions = map.value.getInteractions().getArray()
    interactions.forEach(interaction => {
      if (interaction instanceof Draw) {
        map.value.removeInteraction(interaction)
      }
    })
    
    // 重置绘制状态相关的引用
    hasFeatures.value = false
    
    console.log('已停止所有绘制操作，移除了所有绘制交互')
    alert('已停止所有绘制操作！')
  } else {
    alert('地图未初始化或当前没有正在进行的绘制操作！')
  }
}

// 开始修改要素模式
const startEditFeature = () => {
  if (isEditing.value) {
    stopEditFeature();
    return;
  }

  // 先停止其他交互模式
  stopDrawing();
  if (isDeleting.value) {
    stopDeleteFeature();
  }
  
  // 检查是否有选中的要素
  if (selectedFeatures.value.length === 0) {
    // 如果没有选中要素，先提示用户选择
    alert('请先选择要修改的要素');
    
    // 设置为选择模式
    isEditing.value = true; // 使用editing标志但不立即进入编辑模式
    
    // 创建选择交互让用户选择要素
    if (!selectInteraction) {
      selectInteraction = new Select({
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 0, 0.2)'
          }),
          stroke: new Stroke({
            color: '#ffff00',
            width: 2
          }),
          image: new Circle({
            radius: 6,
            fill: new Fill({
              color: 'rgba(255, 255, 0, 0.5)'
            }),
            stroke: new Stroke({
              color: '#ffff00',
              width: 2
            })
          })
        })
      });
      
      // 监听选择事件
      selectInteraction.on('select', (event) => {
        // 清空之前的选择
        selectedFeatures.value = [];
        // 添加新选择的要素
        event.selected.forEach(feature => {
          selectedFeatures.value.push(feature);
          // 设置当前类型名称（根据选中要素的来源或属性）
          if (!currentTypeName.value) {
            // 尝试从要素或数据源推断类型名称
            if (geoserverWfsSource.value && geoserverWfsSource.value.getFeatures().includes(feature)) {
              // 从WFS源获取的要素，使用配置的默认类型
              currentTypeName.value = 'city'; // 默认类型，可根据实际情况修改
            }
          }
          console.log('选中要修改的要素:', feature.getId());
        });
        
        // 如果已选择要素，自动进入编辑模式
        if (selectedFeatures.value.length > 0) {
          enterEditMode();
        }
      });
      
      map.value.addInteraction(selectInteraction);
    } else {
      selectInteraction.setActive(true);
    }
    
    console.log('请选择要修改的要素');
  } else {
    // 如果已有选中要素，直接进入编辑模式
    enterEditMode();
  }
};

// 进入实际的编辑模式
const enterEditMode = () => {
  if (selectedFeatures.value.length === 0) return;
  
  // 先移除选择交互
  if (selectInteraction) {
    selectInteraction.setActive(false);
  }
  
  // 确定要修改的数据源
  if (vectorSource.value && vectorSource.value.getFeatures().length > 0) {
    modifiedSource = vectorSource.value;
  } else if (geoserverWfsSource.value && geoserverWfsSource.value.getFeatures().length > 0) {
    modifiedSource = geoserverWfsSource.value;
  } else {
    alert('没有可编辑的要素');
    isEditing.value = false;
    return;
  }
  
  // 创建修改交互，只修改选中的要素
  modifyInteraction = new Modify({
    source: modifiedSource,
    features: new Collection(selectedFeatures.value), // 只修改选中的要素
    style: new Style({
      fill: new Fill({
        color: 'rgba(0, 0, 255, 0.2)'
      }),
      stroke: new Stroke({
        color: '#0000ff',
        width: 2
      }),
      image: new Circle({
        radius: 6,
        fill: new Fill({
          color: 'rgba(0, 0, 255, 0.5)'
        }),
        stroke: new Stroke({
          color: '#0000ff',
          width: 2
        })
      })
    })
  });
  
  // 清空之前的修改记录
  modifiedFeatures.value = [];
  
  // 监听修改结束事件
  modifyInteraction.on('modifyend', (event) => {
    console.log('要素修改结束:', event.features.getLength(), '个要素被修改');
    
    // 收集被修改的要素
    event.features.forEach(feature => {
      // 只添加尚未在列表中的要素
      if (!modifiedFeatures.value.includes(feature)) {
        modifiedFeatures.value.push(feature);
        console.log('添加被修改的要素:', feature.getId());
        
        // 设置当前类型名称（根据选中要素的几何类型）
        if (!currentTypeName.value) {
          const geomType = feature.getGeometry().getType();
          currentTypeName.value = typeMap[geomType] || 'city';
        }
      }
    });
  });
  
  // 添加交互到地图
  map.value.addInteraction(modifyInteraction);
  console.log('进入要素编辑模式，正在编辑', selectedFeatures.value.length, '个要素');
  alert('已进入编辑模式，您可以拖动要素修改其位置');
};

// 停止修改要素模式
const stopEditFeature = () => {
  if (modifyInteraction) {
    map.value.removeInteraction(modifyInteraction);
    modifyInteraction = null;
  }
  isEditing.value = false;
  // 不清除modifiedFeatures，以便用户可以保存修改
  console.log('退出要素编辑模式');
};

// 保存修改的要素 - 基于 lzy.vue 的 updateFeature 函数实现
const saveModifiedFeatures = async () => {
  if (modifiedFeatures.value.length === 0) {
    console.log('没有修改的要素需要保存');
    alert('没有修改的要素需要保存');
    return;
  }
  
  try {
    // 为每个修改的要素执行更新
    for (const feature of modifiedFeatures.value) {
      const geometry = feature.getGeometry();
      if (!geometry) {
        throw new Error('无效的几何对象');
      }

      const featureId = feature.getId();
      if (!featureId) {
        console.warn('要素没有ID，跳过更新');
        continue;
      }

      const updatedFeature = new Feature();
      updatedFeature.setId(featureId);
      updatedFeature.setGeometryName('geom');
      
      // 转换几何对象（transformGeometry现在返回克隆并交换坐标后的几何对象）
      const transformedGeometry = transformGeometry(geometry);
      updatedFeature.setGeometry(transformedGeometry);
      
      // 确保保留原始要素的所有属性
      const keys = feature.getKeys();
      keys.forEach(key => {
        if (key !== 'geometry' && key !== 'geom') {
          updatedFeature.set(key, feature.get(key));
        }
      });
      
      // 执行WFS更新请求
      await wfsRequest([updatedFeature], 'update', geometry.getType());
      console.log(`成功更新要素 ID: ${featureId}`);
    }
    
    // 清除修改列表
    modifiedFeatures.value = [];
    
    // 显示成功消息
    console.log('成功保存所有修改的要素');
    alert('要素修改已成功保存！');
    
    // 刷新图层数据
    setTimeout(() => {
      if (vectorSource.value) vectorSource.value.refresh();
      if (geoserverWfsSource.value) geoserverWfsSource.value.refresh();
    }, 1000);
    
  } catch (error) {
    console.error('保存修改失败:', error);
    alert('保存修改失败: ' + error.message);
  }
};

// 取消修改
const cancelModifications = () => {
  // 清除修改列表
  modifiedFeatures.value = [];
  
  // 重新加载数据以恢复原始状态
  if (vectorSource.value) {
    vectorSource.value.clear();
    // 可以选择重新加载数据
  }
  
  alert('修改已取消');
}

// 坐标转换功能函数 - 基于 lzy.vue 实现
function transformCoordinates(coordinates, sourceProj, targetProj) {
  if (Array.isArray(coordinates) && coordinates.length >= 2 && typeof coordinates[0] === 'number') {
    // 直接使用OpenLayers的transform函数进行坐标转换
    const transformed = transform(coordinates, sourceProj, targetProj);
    console.log(`坐标转换: ${coordinates} -> ${transformed}`);
    return transformed; // 直接返回转换后的坐标，不要颠倒顺序
  } else if (Array.isArray(coordinates)) {
    // 对于嵌套数组，递归转换每个坐标
    return coordinates.map(coord => transformCoordinates(coord, sourceProj, targetProj));
  }
  return coordinates;
}

// 更新的几何处理函数 - 修复坐标处理问题
const transformGeometry = (geometry) => {
  if (!geometry) return geometry;
  
  const originalCoordinates = geometry.getCoordinates();
  console.log('原始坐标:', JSON.stringify(originalCoordinates));
  
  // 关键修复：从日志可以看出，GeoServer的WFS-T请求需要[latitude, longitude]格式的坐标
  // 但OpenLayers使用的是[longitude, latitude]格式
  // 因此需要交换坐标顺序后再发送到GeoServer
  
  // 克隆几何对象，避免修改原始几何
  const clonedGeometry = geometry.clone();
  const geometryType = clonedGeometry.getType();
  console.log('几何类型:', geometryType);
  
  // 根据几何类型交换坐标顺序
  if (geometryType === 'Point') {
    const coords = originalCoordinates.slice();
    const swappedCoords = [coords[1], coords[0]];
    clonedGeometry.setCoordinates(swappedCoords);
    console.log('点坐标交换后:', swappedCoords);
  } else if (geometryType === 'LineString' || geometryType === 'MultiLineString') {
    let swappedCoords;
    if (geometryType === 'LineString') {
      swappedCoords = originalCoordinates.map(coord => [coord[1], coord[0]]);
    } else { // MultiLineString
      swappedCoords = originalCoordinates.map(line => 
        line.map(coord => [coord[1], coord[0]])
      );
    }
    clonedGeometry.setCoordinates(swappedCoords);
    console.log('线坐标交换后:', JSON.stringify(swappedCoords));
  } else if (geometryType === 'Polygon' || geometryType === 'MultiPolygon') {
    let swappedCoords;
    if (geometryType === 'Polygon') {
      swappedCoords = originalCoordinates.map(ring => 
        ring.map(coord => [coord[1], coord[0]])
      );
    } else { // MultiPolygon
      swappedCoords = originalCoordinates.map(polygon => 
        polygon.map(ring => ring.map(coord => [coord[1], coord[0]]))
      );
    }
    clonedGeometry.setCoordinates(swappedCoords);
    console.log('面坐标交换后:', JSON.stringify(swappedCoords));
  }
  
  // 返回克隆并交换坐标后的几何对象，保持原始几何不变
  return clonedGeometry;
};

// 统一的几何类型到图层映射函数 - 基于 lzy.vue 实现
function getTargetLayerByGeometry(geometry) {
  const geometryType = geometry.getType();
  if (geometryType === 'Point' || geometryType === 'MultiPoint') {
    return 'city';
  } else if (geometryType === 'MultiLineString' || geometryType === 'LineString') {
    return 'bou2_4l';
  } else if (geometryType === 'MultiPolygon' || geometryType === 'Polygon') {
    return 'bou2_4p';
  }
  console.warn(`不支持的几何类型: ${geometryType}`);
  return 'city'; // 默认返回点图层
}

// 统一的WFS请求发送函数 - 基于 lzy.vue 的 sendWFSRequest 函数实现
const wfsRequest = (features, operation, type) => {
  return new Promise((resolve, reject) => {
    try {
      // 确保features是数组
      if (!Array.isArray(features)) {
        features = [features];
      }
      
      // 验证要素是否有ID（对于update和delete操作必须有ID）
      if ((operation === 'update' || operation === 'delete') && features) {
        const featuresWithoutId = features.filter(feature => !feature.getId());
        if (featuresWithoutId.length > 0) {
          console.error(`${operation}操作需要要素ID，但发现${featuresWithoutId.length}个要素没有ID`);
          // 过滤掉没有ID的要素继续处理
          features = features.filter(feature => feature.getId());
          
          // 如果过滤后没有要素了，返回一个已解决的Promise
          if (features.length === 0) {
            console.warn(`没有有效的${operation}要素，取消WFS请求`);
            resolve('没有有效的要素进行操作');
            return;
          }
        }
      }
      
      // 获取第一个要素的几何类型来确定目标图层
      let targetLayer = 'city'; // 默认值
      if (features.length > 0 && features[0].getGeometry()) {
        targetLayer = getTargetLayerByGeometry(features[0].getGeometry());
      } else if (type) {
        // 如果没有几何对象但提供了类型，使用类型映射
        targetLayer = typeMap[type] || targetLayer;
      }
      console.log(`目标图层: ${targetLayer}`);
      
      const options = {
        featureNS: 'http://web2305.com', // 保持原有的命名空间
        featurePrefix: 'web2305', // 保持原有的前缀
        featureType: targetLayer,
        srsName: 'EPSG:4326'
      };
      
      let wfsTransaction;
      switch (operation) {
        case 'insert':
          wfsTransaction = new WFS().writeTransaction(features, null, null, options);
          break;
        case 'update':
          wfsTransaction = new WFS().writeTransaction(null, features, null, options);
          break;
        case 'delete':
          wfsTransaction = new WFS().writeTransaction(null, null, features, options);
          break;
        default:
          console.error('不支持的操作类型:', operation);
          reject(new Error('不支持的操作类型'));
          return;
      }

      // 序列化XML并添加必要的命名空间声明
      const serializer = new XMLSerializer();
      let xmlString = serializer.serializeToString(wfsTransaction);
      
      // 添加命名空间声明，提高兼容性
      xmlString = xmlString.replace(
        '<Transaction',
        '<Transaction xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:web2305="http://web2305.com"'
      );

      console.log(`发送的WFS-T ${operation} XML请求:`, xmlString);
      
      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/geoserver/web2305/ows?service=WFS', true);
      xhr.setRequestHeader('Content-Type', 'text/xml');
      xhr.send(xmlString);

      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            // 检查响应中是否包含异常信息
            if (xhr.responseText && xhr.responseText.includes('Exception')) {
              console.error(`WFS-T ${operation}事务返回错误:`, xhr.responseText);
              reject(new Error(`GeoServer处理请求时发生错误`));
            } else {
              console.log(`WFS-T ${operation}事务成功:`, xhr.responseText);
              resolve(xhr.responseText);
            }
          } else {
            console.error(`WFS-T ${operation}事务失败:`, xhr.status, xhr.responseText);
            reject(new Error(`WFS操作失败: ${xhr.status} ${xhr.statusText}`));
          }
        }
      };
      
      xhr.onerror = function() {
        console.error('网络错误，无法连接到GeoServer');
        reject(new Error('网络错误，请检查GeoServer连接'));
      };
      
    } catch (error) {
      console.error('WFS请求准备失败:', error);
      reject(error);
    }
  });
}

// 清除矢量图形
const clearDrawing = () => {
  if (vectorSource.value) {
    // 清除所有要素
    vectorSource.value.clear()
    hasFeatures.value = false
  }
}

// 初始化查询弹窗
const initQueryOverlay = () => {
  if (!propertyOverlay.value) {
    propertyOverlay.value = new Overlay({
      element: document.getElementById('query-popup'),
      autoPan: {
        animation: {
          duration: 250,
        },
      },
    })
    map.value.addOverlay(propertyOverlay.value)
  }
}

// 开始点选查询
const startQuerySelect = () => {
  // 先停止其他交互模式
  stopDrawing()
  if (isDeleting.value) {
    stopDeleteFeature()
  }
  if (isEditing.value) {
    stopEditFeature()
  }
  if (queryBoxInteraction.value) {
    map.value.removeInteraction(queryBoxInteraction.value)
    queryBoxInteraction.value = null
  }
  
  // 初始化查询弹窗
  initQueryOverlay()
  
  // 创建点选查询交互
  querySelectInteraction.value = new Select({
    style: new Style({
      fill: new Fill({
        color: 'rgba(0, 0, 255, 0.2)'
      }),
      stroke: new Stroke({
        color: '#0000ff',
        width: 2
      }),
      image: new Circle({
        radius: 6,
        fill: new Fill({
          color: 'rgba(0, 0, 255, 0.5)'
        }),
        stroke: new Stroke({
          color: '#0000ff',
          width: 2
        })
      })
    })
  })
  
  // 添加选择事件监听
  querySelectInteraction.value.on('select', (evt) => {
    const coordinate = evt.mapBrowserEvent.coordinate
    const selectedFeatures = querySelectInteraction.value.getFeatures().getArray()
    
    if (selectedFeatures.length > 0) {
      let propertyText = ''
      selectedFeatures.forEach(feature => {
        // 获取要素的所有属性
        const properties = feature.getProperties()
        // 排除geometry属性
        delete properties.geometry
        
        // 将属性格式化为文本
        const propertyStrings = Object.entries(properties).map(([key, value]) => {
          return `${key}: ${value}`
        })
        
        propertyText += propertyStrings.join('<br>') + '<br><br>'
      })
      
      // 显示属性信息
      document.getElementById('query-popup-content').innerHTML = propertyText
      propertyOverlay.value.setPosition(coordinate)
    } else {
      // 没有选中要素时隐藏弹窗
      propertyOverlay.value.setPosition(null)
    }
  })
  
  map.value.addInteraction(querySelectInteraction.value)
  isQuerying.value = true
  console.log('进入点选查询模式')
}

// 停止点选查询
const stopQuerySelect = () => {
  if (querySelectInteraction.value) {
    map.value.removeInteraction(querySelectInteraction.value)
    querySelectInteraction.value = null
  }
  if (propertyOverlay.value) {
    propertyOverlay.value.setPosition(null)
  }
  isQuerying.value = false
  console.log('退出点选查询模式')
}

// 开始框选查询
const startQueryBox = () => {
  alert('框选查询模式已启动，请按住Ctrl/Cmd键在地图上拖动鼠标进行框选')
  
  // 先停止其他交互模式
  stopDrawing()
  if (isDeleting.value) {
    stopDeleteFeature()
  }
  if (isEditing.value) {
    stopEditFeature()
  }
  if (querySelectInteraction.value) {
    map.value.removeInteraction(querySelectInteraction.value)
    querySelectInteraction.value = null
  }
  
  // 初始化查询弹窗
  initQueryOverlay()
  
  // 创建框选查询交互
  queryBoxInteraction.value = new DragBox({
    condition: platformModifierKeyOnly, // 需要按住修饰键（Ctrl/Cmd）
    style: new Style({
      stroke: new Stroke({
        color: '#0000ff',
        width: 2,
        lineDash: [10, 10]
      }),
      fill: new Fill({
        color: 'rgba(0, 0, 255, 0.1)'
      })
    })
  })
  
  // 监听框选结束事件
  queryBoxInteraction.value.on('boxend', () => {
    const extent = queryBoxInteraction.value.getGeometry().getExtent()
    const center = getCenter(extent)
    
    // 查询与框选范围相交的要素
    let selectedFeatures = []
    
    // 从所有图层中查询相交要素
    map.value.getLayers().forEach(layer => {
      if (layer instanceof VectorLayer && layer.getSource()) {
        const source = layer.getSource()
        source.forEachFeatureIntersectingExtent(extent, (feature) => {
          selectedFeatures.push(feature)
        })
      }
    })
    
    if (selectedFeatures.length > 0) {
      let propertyText = `<div>框选查询结果 (共${selectedFeatures.length}个要素):</div><br>`
      
      selectedFeatures.forEach(feature => {
        // 获取要素的所有属性
        const properties = feature.getProperties()
        // 排除geometry属性
        delete properties.geometry
        
        // 将属性格式化为文本
        const propertyStrings = Object.entries(properties).map(([key, value]) => {
          return `${key}: ${value}`
        })
        
        propertyText += `<div style="border-bottom: 1px solid #eee; padding-bottom: 5px; margin-bottom: 5px;">`
        propertyText += propertyStrings.join('<br>')
        propertyText += '</div><br>'
      })
      
      // 显示属性信息
      document.getElementById('query-popup-content').innerHTML = propertyText
      propertyOverlay.value.setPosition(center)
    } else {
      // 没有选中要素时显示提示
      document.getElementById('query-popup-content').innerHTML = '框选范围内没有找到要素'
      propertyOverlay.value.setPosition(center)
    }
  })
  
  map.value.addInteraction(queryBoxInteraction.value)
  isQuerying.value = true
  console.log('进入框选查询模式，请按住Ctrl/Cmd键拖动框选')
}

// 停止框选查询
const stopQueryBox = () => {
  if (queryBoxInteraction.value) {
    map.value.removeInteraction(queryBoxInteraction.value)
    queryBoxInteraction.value = null
  }
  if (propertyOverlay.value) {
    propertyOverlay.value.setPosition(null)
  }
  isQuerying.value = false
  console.log('退出框选查询模式')
}

// 关闭查询弹窗
const closeQueryPopup = () => {
  if (propertyOverlay.value) {
    propertyOverlay.value.setPosition(null)
  }
}



// 创建底图图层
const createBaseMapLayer = (type) => {
  let url
  switch (type) {
    case 'vector':
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
      break
    case 'image':
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=6&x={x}&y={y}&z={z}'
      break
    case 'terrain':
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=8&x={x}&y={y}&z={z}'
      break
    default:
      url = 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
  }
  
  return new TileLayer({
    source: new XYZ({
      url: url,
      crossOrigin: 'anonymous'
    })
  })
}

// 切换底图
const switchBaseMap = (type) => {
  if (!map.value || currentBaseMap.value === type) return
  
  // 移除当前底图
  const layers = map.value.getLayers()
  layers.forEach((layer, index) => {
    if (index === 0) { // 假设底图是第一个图层
      map.value.removeLayer(layer)
    }
  })
  
  // 添加新底图
  const newBaseMap = createBaseMapLayer(type)
  map.value.getLayers().insertAt(0, newBaseMap)
  
  // 更新当前底图类型
  currentBaseMap.value = type
}

onMounted(() => {
  // 初始化地图
  map.value = new Map({
    target: mapRef.value,
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          crossOrigin: 'anonymous'
        })
      })
    ],
    view: new View({
      center: [104, 35], // 地图中心坐标（经度，纬度）- 设置为中国中心
      zoom: 5,         // 初始缩放级别
      projection: 'EPSG:4326' // 使用WGS84坐标系
    })
  })
  
  // 初始化矢量图层
  initVectorLayer()
})
</script>

<template>
  <div class="map-container">
    <div class="main-content">
      <div class="controls">
        <div class="button-group">
          <button 
            @click="switchBaseMap('vector')" 
            :class="{ active: currentBaseMap === 'vector' }"
            class="map-button"
          >
            矢量底图
          </button>
          <button 
            @click="switchBaseMap('image')" 
            :class="{ active: currentBaseMap === 'image' }"
            class="map-button"
          >
            影像底图
          </button>
          <button 
            @click="switchBaseMap('terrain')" 
            :class="{ active: currentBaseMap === 'terrain' }"
            class="map-button"
          >
            地形底图
          </button>
        </div>
        <div class="button-group">
          <button 
            @click="toggleWmsLayer" 
            :class="{ active: isWmsLayerVisible }"
            class="geoserver-button"
          >
            {{ isWmsLayerVisible ? '隐藏WMS图层' : '显示WMS图层' }}
          </button>
          <button 
            @click="toggleWfsLayer" 
            :class="{ active: isWfsLayerVisible }"
            class="geoserver-button"
          >
            {{ isWfsLayerVisible ? '隐藏WFS图层' : '显示WFS图层' }}
          </button>
        </div>
        <div class="button-group">
          <button @click="addFeature('city')">添加点</button>
          <button @click="addFeature('bou2_4l')">添加线</button>
          <button @click="addFeature('bou2_4p')">添加面</button>
          <button @click="stopDrawing" class="stop-button">停止绘制</button>
        </div>
        <div class="button-group">
          <button @click="clearDrawing" :disabled="!hasFeatures">
            清除绘制
          </button>
        </div>
        <div class="button-group">
          <button 
            @click="startDeleteFeature" 
            :class="{ active: isDeleting }"
            class="delete-button"
          >
            {{ isDeleting ? '取消删除' : '删除要素' }}
          </button>
          <button 
            @click="deleteSelectedFeatures" 
            :disabled="!selectedFeatures.length"
            class="delete-button"
          >
            删除选中要素 ({{ selectedFeatures.length }})
          </button>
        </div>
        
        <div class="button-group">
          <button 
            @click="startEditFeature"
            :class="['map-button', { active: isEditing }]"
            :data-edit="isEditing"
          >
            {{ isEditing ? '取消编辑' : '修改要素' }}
          </button>
          <button 
            @click="saveModifiedFeatures"
            class="map-button"
            :disabled="!isEditing || modifiedFeatures.length === 0"
          >
            保存修改
          </button>
          <button 
            @click="cancelModifications"
            class="map-button"
            :disabled="modifiedFeatures.length === 0"
          >
            取消修改
          </button>
        </div>
        <div class="button-group">
          <button @click="uploadToGeoserver" :disabled="!hasFeatures" class="geoserver-button">
            上传到GeoServer
          </button>
        </div>
        <div class="button-group">
          <button 
            @click="startQuerySelect" 
            :class="{ active: isQuerying && querySelectInteraction }"
            class="query-button"
          >
            点选查询
          </button>
          <button 
            @click="startQueryBox" 
            :class="{ active: isQuerying && queryBoxInteraction }"
            class="query-button"
          >
            框选查询
          </button>
          <button 
            @click="stopQuerySelect" 
            v-if="isQuerying && querySelectInteraction"
            class="stop-button"
          >
            停止查询
          </button>
          <button 
            @click="stopQueryBox" 
            v-if="isQuerying && queryBoxInteraction"
            class="stop-button"
          >
            停止查询
          </button>
        </div>
      </div>
      <div ref="mapRef" class="map"></div>
    </div>
  </div>
  
  <!-- 查询结果弹窗 -->
  <div id="query-popup" class="query-popup">
    <a href="#" id="query-popup-closer" class="query-popup-closer" @click="closeQueryPopup"></a>
    <div id="query-popup-content" class="query-popup-content"></div>
  </div>
  
  <!-- 使用封装的对话框组件 -->
  <FeatureEditDialog
    v-model:visible="dialogVisible"
    :current-type-name="currentTypeName"
    :feature-properties="featureProperties"
    @submit="handleFeatureSubmit"
    @cancel="handleFeatureCancel"
  />
</template>

<style scoped>
@import '../css/ditu.css';
</style>